package com.home.dao;

import com.home.entity.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
@Controller
public class StudentDaoimpl implements StudentDao {
    private JdbcTemplate jdbcTemplate;
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public List<Student> findAllStudent() {
        String sql = "select * from sign_up";
        List<Student> list = jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<Student>(Student.class));
        return list;
    }

    public int addStudent(final Student students) {
        final String sql = "INSERT INTO sign_up(user_name,QQ,stu_type,join_date,school,student_num,url," +
                "hope,bro,know_where,create_at,update_at)values(?,?,?,?,?,?,?,?,?,?,?,?)";
        KeyHolder kh = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql,new String[]{"id"});
                ps.setString(1,students.getUser_name());
                ps.setString(2,students.getQQ());
                ps.setString(3,students.getStu_type());
                ps.setString(4,students.getJoin_date());
                ps.setString(5,students.getSchool());
                ps.setInt(6,students.getStudent_num());
                ps.setString(7,students.getUrl());
                ps.setString(8,students.getHope());
                ps.setString(9,students.getBro());
                ps.setString(10,students.getKnow_where());
                ps.setLong(11,System.currentTimeMillis());
                ps.setLong(12,System.currentTimeMillis());
                ps.execute();
                return ps;
            }
        },kh);
        return kh.getKeys().size();
    }
}
